package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.TypeDoubleSelectAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.Type;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;

/**
 * 更多分类
 * 
 * @author xi
 * 
 */
public class MoreTypeActivity extends Activity implements OnClickListener {

	private ListView typeListView;
	private ListView subTypeListView;
	private List<String> typeList, subTypeList;
	private TypeDoubleSelectAdapter typeAdapter, subTypeAdapter;

	private RelativeLayout left, right;
	private TextView center_tv;
	private ImageView right_img;
	private TextView reg_tv;
	private Context context;

	private final int GET_TYPE_SUCCESS = 0x1120;
	private final int GET_TYPE_FAIL = GET_TYPE_SUCCESS + 1;
	private List<Type> list;
	private List<Type> subList;
	private LinearLayout type_ll;
	private RelativeLayout progress_layout;

	private LinearLayout loading_dialog_content_layout;
	private RelativeLayout loading_staus_rl;
	private TextView status_tv;

	private ImageButton left_ib;
	private SharePreferenceUtil util;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_moretype);
		util = new SharePreferenceUtil(this, "setting");
		list = new ArrayList<Type>();
		subList = new ArrayList<Type>();
		this.context = this;
		initTitle();
		initRes();
		obtainType();
	}

	private void initTitle() {

		left = (RelativeLayout) findViewById(R.id.left);
		right = (RelativeLayout) findViewById(R.id.right);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("更多");
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
	}

	private int code = -1;

	@Override
	protected void onResume() {

		super.onResume();
		code = getIntent().getIntExtra("code", -1);
	}

	private void initRes() {
		typeListView = (ListView) findViewById(R.id.tc_select_listview);
		subTypeListView = (ListView) findViewById(R.id.tc_select_subListView);
		typeAdapter = new TypeDoubleSelectAdapter(this, list);
		typeAdapter.setSub(false);
		typeAdapter.setPosition(0);
		typeListView.setAdapter(typeAdapter);
		typeListView.setOnItemClickListener(typeItemClickListener);
		subTypeAdapter = new TypeDoubleSelectAdapter(this, subList);
		subTypeListView.setAdapter(subTypeAdapter);
		subTypeListView.setOnItemClickListener(subTypeItemClickListener);
		subTypeAdapter.setSub(true);
		subTypeAdapter.setPosition(0);
		type_ll = (LinearLayout) findViewById(R.id.type_ll);
		progress_layout = (RelativeLayout) findViewById(R.id.progress_layout);
		progress_layout.setOnClickListener(this);
		loading_dialog_content_layout = (LinearLayout) findViewById(R.id.loading_dialog_content_layout);
		loading_staus_rl = (RelativeLayout) findViewById(R.id.loading_staus_rl);
		loading_staus_rl.setVisibility(View.GONE);// 内容提示
		loading_dialog_content_layout.setVisibility(View.VISIBLE);// 加载条
		status_tv = (TextView) findViewById(R.id.status_tv);
	}

	OnItemClickListener typeItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			Type type = list.get(position);
			typeAdapter.setSub(false);
			typeAdapter.setPosition(position);
			subList = type.getSubTypeList();
			subTypeAdapter.setDataChange(subList);

		}
	};
	OnItemClickListener subTypeItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			if (code == 1) {
				Type type = subList.get(position);
				Intent intent = new Intent();
				intent.putExtra("type", type);
				setResult(RESULT_OK, intent);
				finish();
			} else {
				Type type = subList.get(position);
				Intent intent = new Intent(MoreTypeActivity.this,
						ListDisplayActivity.class);
				intent.putExtra("type", type);
				startActivity(intent);
			}

		}
	};

	private void obtainType() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {

					String cacheRes = util.loadStringSharedPreference("type");
					if (null != cacheRes && cacheRes.trim().length() > 0) {
						parserJsonData(cacheRes);
					} else {
						String result = HttpClientUtil.getFromWebByHttpClient(
								context, Urls.GET_ALL_TYPE);
						if (result == null) {
							Message msg = handler.obtainMessage();
							msg.what = GET_TYPE_FAIL;
							handler.sendMessage(msg);
						} else {
							util.removeKey("type");
							util.saveSharedPreferences("type", result);
							GsooApplication.cacaheMap.put(Urls.GET_ALL_TYPE,
									result);
							parserJsonData(result);
						}
						LogUtil.d("wxf", "result" + result);
					}

				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = GET_TYPE_FAIL;
					handler.sendMessage(msg);
					LogUtil.d("wxf", "result:" + e.toString());
				}
			}
		}).start();
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case GET_TYPE_SUCCESS:
				if (list.size() > 0) {
					type_ll.setVisibility(View.VISIBLE);
					progress_layout.setVisibility(View.GONE);
					typeAdapter.setDataChange(list);
					subList = list.get(0).getSubTypeList();
					subTypeAdapter.setDataChange(subList);
				} else {
					status_tv.setText("暂无类型数据");
					loading_staus_rl.setVisibility(View.VISIBLE);
					loading_dialog_content_layout.setVisibility(View.GONE);
					progress_layout.setClickable(false);
				}
				break;
			case GET_TYPE_FAIL:
				if (msg.obj != null) {
					status_tv.setText(msg.obj.toString());
				} else {
					status_tv.setText("加载失败,点击我重新加载");
				}
				loading_staus_rl.setVisibility(View.VISIBLE);
				loading_dialog_content_layout.setVisibility(View.GONE);
				break;
			}
		};
	};

	/**
	 * 数据json解析
	 * 
	 * @throws Exception
	 */
	private void parserJsonData(String result) throws Exception {

		JSONObject obj = new JSONObject(result);
		int state = obj.getInt("state");
		String message = obj.getString("message");
		if (state == 200) {
			JSONArray array = obj.getJSONArray("rows");
			for (int i = 0; i < array.length(); i++) {
				Type type = new Type();
				JSONObject typeObj = array.getJSONObject(i);
				if (!typeObj.isNull("areaId")) {
					type.setAreaId(typeObj.getString("areaId"));
				}
				type.setId(typeObj.getString("id"));
				type.setTypeName(typeObj.getString("typeName"));
				List<Type> subList = new ArrayList<Type>();
				if (!typeObj.isNull("subTypeArray")) {
					JSONArray subArray = typeObj.getJSONArray("subTypeArray");
					for (int j = 0; j < subArray.length(); j++) {
						JSONObject subObj = subArray.getJSONObject(j);
						Type subType = new Type();
						subType.setId(subObj.getString("id"));
						subType.setTypeName(subObj.getString("typeName"));
						subList.add(subType);
					}
				}
				type.setSubTypeList(subList);
				list.add(type);
			}
			Message msg = handler.obtainMessage();
			msg.what = GET_TYPE_SUCCESS;
			handler.sendMessage(msg);

		} else {
			Message msg = handler.obtainMessage();
			msg.what = GET_TYPE_FAIL;
			msg.obj = message;
			handler.sendMessage(msg);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.left_ib:
			if (code == 1) {
				finish();
			} else {
				Intent intent = new Intent(MoreTypeActivity.this,
						HomeActivity.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.progress_layout:
			progress_layout.setVisibility(View.VISIBLE);
			loading_staus_rl.setVisibility(View.GONE);// 内容提示
			loading_dialog_content_layout.setVisibility(View.VISIBLE);// 加载条
			obtainType();
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (code == 1) {
				finish();
			} else {
				Intent intent = new Intent(MoreTypeActivity.this,
						HomeActivity.class);
				startActivity(intent);
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
